import React, { Component } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import { getCheckedValue } from './utils';
import './style.less';

export default class RadioGroup extends Component {
    static propTypes = {
        // eslint-disable-next-line react/require-default-props
        value: PropTypes.any,
        defaultValue: PropTypes.oneOfType([
            PropTypes.string,
            PropTypes.number,
        ]),
        children: PropTypes.node,
        onChange: PropTypes.func,


        className: PropTypes.string,
    };


    static defaultProps = {
        onChange: null,
        defaultValue: null,
        children: null,
        className: null,
    };

    static childContextTypes = {
        radioGroup: PropTypes.any,
    };

    constructor(props) {
        super(props);
        let value;
        if ('value' in props) {
            value = props.value;
        } else if ('defaultValue' in props) {
            value = props.defaultValue;
        } else {
            const checkedValue = getCheckedValue(props.children);
            value = checkedValue && checkedValue.value;
        }
        this.state = {
            value,
        };
    }

    static getDerivedStateFromProps(nextProps) {
        if ('value' in nextProps) {
            return {
                value: nextProps.value,
            };
        }
        const checkedValue = getCheckedValue(nextProps.children);
        if (checkedValue) {
            return {
                value: checkedValue.value,
            };
        }

        return null;
    }

    getChildContext() {
        return {
            radioGroup: {
                onChange: this.onRadioChange,
                value: this.state.value,
            },
        };
    }

    onRadioChange = (ev) => {
        const lastValue = this.state.value;
        const { value } = ev.target;
        if (!('value' in this.props)) {
            this.setState({
                value,
            });
        }

        const { onChange } = this.props;
        if (onChange && value !== lastValue) {
            onChange(ev);
        }
    };


    renderGroup = () => {
        const { props: { children, className } } = this;

        return (
            <div
                className={cx('wpt-radio-group', className)}
            >
                {children}
            </div>
        );
    };

    render() {
        return this.renderGroup();
    }
}
